<template>
  <div id="eqRunningRecordDiv">
    <Breadcrumb content="运行记录" />
    <div class="bodyContent">
      <Splitpanes horizontal class="horizontalLine">
        <Pane size="100">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findRunningRecordList" @keyup="keyupEnter" @search-click="findRunningRecordList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" :loading="tloading" @click="findRunningRecordList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="添加" @click="addRunningRecordDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchRunningRecord"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="eqRunningRecordTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="runningRecordList" :loading="tloading" @current-change="runningRecordRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="30" title=""></vxe-column>
              <vxe-column type="checkbox" width="30"></vxe-column>

              <vxe-column field="runningNo" title="运行单号" width="150">
                <template #default="{ row }">
                  <el-link type="primary" :underline="false" @click="editRunningRecord(row)">
                    <span> {{ row.runningNo}}</span>
                  </el-link>
                </template>
              </vxe-column>
              <vxe-column field="equiptCode" title="设备编码" width="100">
              </vxe-column>
              <vxe-column field="equiptName" title="设备名称" width="100">
              </vxe-column>
              <vxe-column field="specification" title="设备型号" width="150">
              </vxe-column>
              <vxe-column field="repairType" title="班次" width="150">
                <template #default="{ row }">
                  <span>{{ formatCommon(runningClassesList, row.classes) }}</span>
                </template>
              </vxe-column>

              <vxe-column field="startPersonName" title="开机人" width="150"></vxe-column>
              <vxe-column field="shutPersonName" title="关机人" width="150"> </vxe-column>
              <vxe-column field="startDate" title="开始时间" width="150"></vxe-column>
              <vxe-column field="endDate" title="结束时间" width="150"> </vxe-column>

              <vxe-column field="workHours" title="作业时长" width="100"></vxe-column>
              <vxe-column field="planWorkHours" title="计划运行时长" width="100"> </vxe-column>
              <vxe-column field="realWorkHours" title="实际运行时长" width="100"></vxe-column>
              <vxe-column field="stopHours" title="停用时长" width="100"> </vxe-column>
              <vxe-column field="workLoad" title="工作量" width="100"> </vxe-column>

            </vxe-table>
            <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                    'PrevJump',
                    'PrevPage',
                    'Number',
                    'NextPage',
                    'NextJump',
                    'Sizes',
                    'FullJump',
                    'Total'
                  ]" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
      </Splitpanes>
    </div>

  </div>
</template>
    
    <script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
let { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store'; //'../../../stores/store';
import { isEmpty } from 'lodash';

// 全局变量定义区 ==========
let searchForm = {
  searchValue: '',
  planStatus: ''
};
let tloading = ref(false); //加载状态
let runningRecordList: any = reactive([]);
let runningClassesList: any = reactive([]);
let sltRunningRecord: any = ref({});

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  if (!isEmpty(proxy.$route.query.pageSize)) {
    page.pageSize = parseInt(proxy.$route.query.pageSize.toString(), 10);
  }
  if (!isEmpty(proxy.$route.query.pageIndex)) {
    page.currentPage = parseInt(proxy.$route.query.pageIndex.toString(), 10);
  }

  if (!isEmpty(proxy.$route.query.planId)) {
    sltRunningRecord.value.id = proxy.$route.query.planId.toString();
  }
  getDictItemsList(); //批量获取字典
  findRunningRecordList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['runningClasses'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });

  const runningClassess = dictTreeTypeItems.data.find((item: any) => item.code === 'runningClasses');
  runningClassesList.push(...runningClassess.detailDataList);
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findRunningRecordList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findRunningRecordList();
}

function findRunningRecordList() {
  tloading.value = true;
  runningRecordList.length = 0; //放入数据前清空数据
  const url = '/api/eq/eqRunningRecord/findRunningRecordPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      runningRecordList.push(...res.data.records);
      page.totalResult = res.data.total;

      const kn = runningRecordList.find((k: any) => k.id == sltRunningRecord.value.id);
      if (isEmpty(kn)) {
        runningRecordRowClick({ row: runningRecordList[0] }); //默认选中第一条数据
      } else {
        runningRecordRowClick({ row: kn }); //默认选中第一条数据
      }

      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}
function runningRecordRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltRunningRecord.value = {};
    runningRecordList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.eqRunningRecordTableRef as any).setCurrentRow(row);
    sltRunningRecord.value = row;
  }
}

function addRunningRecordDialog() {
  const data = {
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqRunningRecord'
  };
  proxy.$router.push({ path: '/eqRunningRecordEdit', query: data });
}

function editRunningRecord(row: any) {
  const data = {
    id: row.id,
    pageIndex: page.currentPage.toString(),
    pageSize: page.pageSize.toString(),
    url: '/eqRunningRecord'
  };
  proxy.$router.push({ path: '/eqRunningRecordEdit', query: data });
}

function deleteBatchRunningRecord() {
  const sltRunningRecords = (proxy.$refs.eqRunningRecordTableRef as any).getCheckboxRecords();
  if (!(sltRunningRecords.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delRunningRecordList = sltRunningRecords.filter((p: any) => !isEmpty(p.id));
        if (delRunningRecordList.length > 0) {
          const data = { eqRunningRecordList: delRunningRecordList };
          const url = '/api/eq/eqRunningRecord/batchDeleteRunningRecordList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findRunningRecordList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>
    
<style lang="scss" scoped>
#eqRunningRecordDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .elTagClazz {
        margin-left: 5px;
        cursor: pointer;
      }
      .selectedElTagClazz {
        margin-left: 5px;
        cursor: pointer;
        background-color: #89d7fc;
      }
    }
    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px - 32px);
    }
    // 质控靶值设定弹框表格
    .tableTargetBody {
      height: 600px;
      .tableTargetBodyRight {
        height: calc(100% - 2px);
        border: 1px solid #e8eaec;

        .closeBtn {
          margin-left: 720px;
        }
      }
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }
    .el-form {
      padding-right: 15px;
      .el-form-item--large {
        margin-bottom: 10px;
      }
      .el-button {
        padding: 5px 2px !important;
      }
      :deep(.el-input__inner) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      padding: 10px;
    }
    // 最右侧质控项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
    .el-link_clazz {
      margin-right: 5px;
    }
  }
}
</style>